package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.List;

/**
 * 体检套餐
 */

@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private SetmealService setmealService;
    //获取所有套餐信息
    @RequestMapping("/getSetmeal")
    public Result getSetmeal(){
        ObjectMapper mapper=new ObjectMapper();
//        List<Setmeal> list = setmealService.findAll();
//        return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,list);
        try{
          String setmealjson=jedisPool.getResource().get(RedisConstant.SETMEAL_BASE);
          if (setmealjson!=null){
              return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,setmealjson);
          }
          else {
              List<Setmeal> list = setmealService.findAll();
                  setmealjson=mapper.writeValueAsString(list);
              jedisPool.getResource().setex(RedisConstant.SETMEAL_BASE,600000000,setmealjson);
              return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,setmealjson);
          }

        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }

    //根据套餐id查询套餐详情，包含（套餐基本信息、套餐关联的检查组、检查组关联的检查项）
    @RequestMapping("/findById")
    public Result findById(Integer id){
        ObjectMapper mapper=new ObjectMapper();
        try{
           String detailJson= jedisPool.getResource().get(RedisConstant.SETMEAL_DETAIL+id);
           if (detailJson!=null){
               return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,detailJson);
           }
           else {
               Setmeal setmeal = setmealService.findById(id);
               detailJson=mapper.writeValueAsString(setmeal);
               jedisPool.getResource().setex(RedisConstant.SETMEAL_DETAIL+id,60000000,detailJson);
               return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,detailJson);
           }
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }
}
